package cn.mw.cmdb.virtualization.service.handler;

import cn.mw.cmdb.param.zabbixResult.MWItemHistoryDTO;
import cn.mw.cmdb.virtualization.dto.HistoryOrTrendDto;
import cn.mw.cmdb.virtualization.dto.ItemLatestConvertDto;
import cn.mw.cmdb.virtualization.service.ZabbixMonitorHandler;
import cn.mw.main.api.common.ZabbixDubboService;
import cn.mw.microMonitorCommon.constants.ZabbixApiConstants;
import cn.mw.microMonitorCommon.entity.zabbix.MWZabbixAPIResult;
import cn.mw.microMonitorCommon.util.DateUtils;
import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @description zabbix历史数据处理
 */
@Slf4j
@Data
public class ZabbixHistoryHandler implements ZabbixMonitorHandler {

    private ZabbixDubboService zabbixDubboService;
    private int monitorServerId;
    private List<String> itemNames;
    private List<String> hostIds;
    private Long startTime;
    private Long endTime;

    public ZabbixHistoryHandler(ZabbixDubboService zabbixDubboService, int monitorServerId, List<String> itemNames, List<String> hostIds, Long startTime, Long endTime) {
        this.zabbixDubboService = zabbixDubboService;
        this.monitorServerId = monitorServerId;
        this.itemNames = itemNames;
        this.hostIds = hostIds;
        this.startTime = startTime;
        this.endTime = endTime;
    }

    @Override
    public List<HistoryOrTrendDto> handle(Integer groupCount) {
        List<HistoryOrTrendDto> dtos = new ArrayList<>();
        List<ItemLatestConvertDto> applications = new ArrayList<>();
        //查询zabbix最新数据返回
        List<List<String>> hosts = Lists.partition(hostIds, groupCount);
        for (List<String> host : hosts) {
            MWZabbixAPIResult mwZabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.ITEM_GET_BY_SEARCH, monitorServerId, itemNames, host);
            if(mwZabbixAPIResult == null || mwZabbixAPIResult.isFail()){continue;}
            applications.addAll(JSONArray.parseArray(String.valueOf(mwZabbixAPIResult.getData()), ItemLatestConvertDto.class));
        }
        if(CollectionUtils.isEmpty(applications)){return null;}
        List<MWItemHistoryDTO> historyApplications = new ArrayList<>();
        //按照值类型分组
        Map<String, List<String>> valueTypeMap = applications.stream().collect(Collectors.groupingBy(ItemLatestConvertDto::getValue_type, Collectors.mapping(ItemLatestConvertDto::getItemid, Collectors.toList())));
        for (Map.Entry<String, List<String>> entry : valueTypeMap.entrySet()) {
            List<List<String>> itemIdss = Lists.partition(entry.getValue(), groupCount);
            for (List<String> items : itemIdss) {
                MWZabbixAPIResult mwZabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.HISTORY_GET_BY_TIME_AND_TYPE, monitorServerId, items, startTime, endTime, Integer.parseInt(entry.getKey()));
                if(mwZabbixAPIResult == null || mwZabbixAPIResult.isFail()){continue;}
                historyApplications.addAll(JSONArray.parseArray(String.valueOf(mwZabbixAPIResult.getData()), MWItemHistoryDTO.class));
            }
        }
        if(CollectionUtils.isEmpty(historyApplications)){return null;}
        Map<String,ItemLatestConvertDto> itemApplicationMap = new HashMap<>();
        applications.forEach(item->{
            itemApplicationMap.put(item.getItemid(),item);
        });
        for (MWItemHistoryDTO historyDTO : historyApplications) {
            HistoryOrTrendDto dto = new HistoryOrTrendDto();
            ItemLatestConvertDto convertDto = itemApplicationMap.get(historyDTO.getItemid());
            dto.setUnit(convertDto.getUnits());
            String name = convertDto.getName();
            if(name.contains("]")){
                dto.setName(name.substring(name.indexOf("[")+1,name.indexOf("]")));
                dto.setItemName(name.split("]")[1]);
            }else{
                dto.setItemName(name);
            }
            dto.setAvgValue(historyDTO.getValue());
            dto.setClock(historyDTO.getClock());
            dto.setDate(DateUtils.formatDateTime(new Date(Long.parseLong(historyDTO.getClock()) * 1000)));
            dtos.add(dto);
        }
        return dtos;
    }
}
